package com.itheima.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Bean对象工厂
 * 计算机英文：可重复使用的组件
 * 1.需要一个配置文件
 * 2.读取配置文件
 */
public class BeanFactory {

    private static Properties properties;

    private static Map<String, Object> beans;

    static {
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("init error");
        }
        beans = new HashMap<String, Object>();
        Enumeration keys = properties.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement().toString();
            String value = properties.getProperty(key);
            try {
                Object object = Class.forName(value).newInstance();
                beans.put(key, object);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    public static Object getBean(String key) {

        return beans.get(key);

//        Object bean = null;
//        String property = properties.getProperty(name);
//        try {
//            bean = Class.forName(property).newInstance();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        }
//        return bean;
    }
}
